package com.foxmail.aroundme.youtubedemo;


import android.os.Bundle;
import android.util.Log;

import com.foxmail.aroundme.youtubedemo.utils.Config;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;


/**
 * Created by gzl on 2016/10/19.
 */

public class VideoFragment extends YouTubePlayerFragment
        implements YouTubePlayer.OnInitializedListener,
        YouTubePlayer.PlayerStateChangeListener{

    private static VideoFragment videoFragment;
    private YouTubePlayer youTubePlayer;
    private YouTubePlayer.PlayerStateChangeListener listener;
    private String id;

    private VideoFragment(){}

    public static VideoFragment getInstance(){
        if(videoFragment == null){
            synchronized (VideoFragment.class){
                if(videoFragment == null){
                    videoFragment = new VideoFragment();
                }
            }
        }
        Log.d("msg", "videoFragment hashcode = " + videoFragment.hashCode());
        return videoFragment;
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        initialize(Config.KEY, this);
        Log.d("msg", "onCreate");
    }
    @Override
    public void onDestroy() {
        Log.d("msg", "onDestory" );

        super.onDestroy();
    }

    public void play(String id){
        this.id = id;
    }


    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        Log.d("msg", "onInitializationSuccess");
        if(!b){
            this.youTubePlayer = youTubePlayer;
            this.youTubePlayer.setPlayerStateChangeListener(this);
            this.youTubePlayer.loadVideo(id);
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        youTubePlayer = null;

        if (youTubeInitializationResult.isUserRecoverableError()) {
            Log.d("msg", "is user error");
        } else {
            Log.d("msg", "onInitialization Failure" + youTubeInitializationResult.toString());
        }
    }

    @Override
    public void onLoading() {
        Log.d("msg", "onLoading");
    }

    @Override
    public void onLoaded(String s) {
        Log.d("msg", "onLoaded");
    }

    @Override
    public void onAdStarted() {
        Log.d("msg", "onAdStarted");
    }

    @Override
    public void onVideoStarted() {
        Log.d("msg", "onVideoStarted");
    }

    @Override
    public void onVideoEnded() {
        Log.d("msg", "onVideoEnded");
    }

    @Override
    public void onError(YouTubePlayer.ErrorReason errorReason) {
        Log.d("msg", "onError");
    }

}
